#import "FlutterLocationPlugin.h"
#import <CoreLocation/CoreLocation.h>
#import <objc/message.h>


@interface FlutterLocationPlugin()<CLLocationManagerDelegate>
{
    CLLocationManager *locationmanager;//定位服务
}

typedef void (^LocationSuccess)(id _Nullable result);

@property (nonatomic , strong) LocationSuccess cityBlock;

@end

@implementation FlutterLocationPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"flutter_location_plugin"
            binaryMessenger:[registrar messenger]];
  FlutterLocationPlugin* instance = [[FlutterLocationPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getPlatformVersion" isEqualToString:call.method]) {
    result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  }else if ([@"getLocation" isEqualToString:call.method]){
      self.cityBlock = result;
      [self getLocation];
  } else {
    result(FlutterMethodNotImplemented);
  }
}


-(void)getLocation
{
    //判断定位功能是否打开
    if ([CLLocationManager locationServicesEnabled]) {
        locationmanager = [[CLLocationManager alloc]init];
        locationmanager.delegate = self;
        [locationmanager requestAlwaysAuthorization];
        [locationmanager requestWhenInUseAuthorization];

        //设置寻址精度
        locationmanager.desiredAccuracy = kCLLocationAccuracyBest;
        locationmanager.distanceFilter = 5.0;
        [locationmanager startUpdatingLocation];
       
    }
   
}

#pragma mark 定位成功后则执行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [locationmanager stopUpdatingHeading];
    //旧址
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //打印当前的经度与纬度
    NSLog(@"%f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    
    //反地理编码
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
         if (placemarks.count > 0){
             CLPlacemark *placemark = [placemarks objectAtIndex:0];
             //获取城市
             NSString *city = placemark.locality;
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
             }
             NSString *addressStr = [NSString stringWithFormat:@"%@ %@ %@ %@",placemark.administrativeArea,city,placemark.subLocality,placemark.name];
             
//             NSLog(@"city = %@", city);//沈阳市
//             NSLog(@"--%@",placemark.name);//黄河大道21号
//             NSLog(@"++++%@",placemark.subLocality); //浑南区
//             NSLog(@"country == %@",placemark.country);//中国
//             NSLog(@"administrativeArea == %@",placemark.administrativeArea); //辽宁省
//             NSLog(@"administrativeArea == %@",addressStr);
             
             NSDictionary *citDic = @{
                 @"city":[NSString stringWithFormat:@"%@",city],
                 @"name":[NSString stringWithFormat:@"%@",placemark.name],
                 @"subLocality":[NSString stringWithFormat:@"%@",placemark.subLocality],
                 @"country":[NSString stringWithFormat:@"%@",placemark.country],
                 @"administrativeArea":[NSString stringWithFormat:@"%@",placemark.administrativeArea],
                 @"addressStr":[NSString stringWithFormat:@"%@",addressStr],
             };
             self.cityBlock(citDic);
         }
         else if (error == nil && [placemarks count] == 0)
         {
             NSLog(@"No results were returned.");
         }
         else if (error != nil)
         {
             NSLog(@"An error occurred = %@", error);
         }
    }];
    
}



@end
